///////////// Volume ///////////////

var volume = 0.5

function showVolumeWidget() {
	$("#volume").removeClass("hide");
}

function hideVolumeWidget() {
	$("#volume").addClass("hide");
}

function _updateVolumeWidget() {
	$("#volume .progress .bar").css("width", volume*100 + "%");
}

function updateVolumeWidget() {
	var dohide = $("#volume").hasClass("hide");
	showVolumeWidget()
	setTimeout(_updateVolumeWidget, 100);
	if(dohide) {
		setTimeout(hideVolumeWidget, 3000);
	}
}

function volup() {
	if(volume < 1) {
		volume += 0.1;
		if(typeof video != 'undefined') {
			video.volume = volume
		}
	}
	updateVolumeWidget();
}

function voldown() {
	if(volume > 0) {
		volume -= 0.1;
		if(typeof video != 'undefined') {
			video.volume = volume
		}
	}
	updateVolumeWidget();
}

////////////// update /////////////////

var updates = []
function update(id, url, _keyevents) {
	_id = id;
	id = "#" + id;
	console.log(url);
	if(url == null) {
		keyevents = _keyevents;
		$(id).empty();
		return;
	}

	$.get(url, function(data) {
		// register default key events
		var _keyevents = keyevents;
		console.log(keyevents[keys.up]);
		keyevents = new Array();
		keyevents[keys.up] = prevAnchor;
		keyevents[keys.down] = nextAnchor;
		keyevents[keys.back] = goBack;
		keyevents[keys.left] = voldown;
		keyevents[keys.right] = volup;

		console.log(data);

		var wasempty = $(id).is(":empty");
		console.log(wasempty);

		$(id).find("*").remove();
		$(id).html(data);
		$(id).data("url", url);
		if(wasempty) {
			updates.push({id: _id, url: null, keyevents: _keyevents});
		}
		updates.push({id: _id, url: url, keyevents: null});
		$("[tabindex]").first().focus(); // TODO does not seem to work in chrome
		$("[tabindex]").mouseenter(function(event){
			event.delegateTarget.focus();
		});
	});
}

/*window.onpopstate = function(event) {
	update(event.state.id, event.state.url, true);
}*/

function canGoBack() {
	return updates.length > 1
}

function goBack() {
	if(canGoBack()) {
		updates.pop()
		var lastupdate = updates.pop()
		update(lastupdate.id, lastupdate.url, lastupdate.keyevents);
	}
}

function nextTabindex(down) {
	focus = $(":focus").attr("tabindex");
	if(down) {
		return focus + 1;
	}
	return focus - 1;
}

function prevAnchor() {
	$("*[tabindex=" + nextTabindex(false) + "]").focus();
}

function nextAnchor() {
	$("*[tabindex=" + nextTabindex(true) + "]").focus();
}

// keys
var keys = {up: 38, down: 40, back: 66, ok: 13, left: 37, right: 39, osd: 77};
var keyevents = new Array();

$(document.documentElement).keyup(function (event) {
	if(event.keyCode in keyevents) {
		keyevents[event.keyCode]();
	}
	return false;
});
update("body", "home");

$(document).ready(function() {
	// do stuff when DOM is ready
});
